var express = require('express');
var app = express();
var server = app.listen(3000);
var path = require('path');
var client = require('redis').createClient(6379,'127.0.0.1');
var redis_cli = require('./libraries/redis_ci').ci_redis;
var socketIo = require('./libraries/socketIo');
var io=socketIo.socketIo(server);
var request = require('request');

var base_url = 'http://paintmore.cn/';
var login = 'auth/login';



app.engine('ejs', require('ejs-locals'));
app.set('views',  './template');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));

app.get("/",function (req, res) {
    var Cookies = {};
    req.headers.cookie && req.headers.cookie.split(';').forEach(function( Cookie ) {
        var parts = Cookie.split('=');
        Cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
    })
    redis_cli.session(client,Cookies.ci_session,function(response){
        if(!response){
            res.redirect(base_url+login);
        }else{
            var userSerialize = require('./libraries/getCiUser').getUser(response,'login_user');
            if(!userSerialize){
                res.redirect(base_url+login);
            }else {
                var user = require('./libraries/serialize').unserialize(userSerialize);
                var users={
                    user_id:user.user_id,
                    user_name:user.username,
                    user_type:'public'
                };
                //todo:分配客服,并且将客服状态设置为忙,修正为redis
                request.get(base_url+'api/helper/get_helper',function(error, rsp, body){
                    //console.log(base_u)
                    if (!error && rsp.statusCode == 200) {
                        console.log(body)
                        var helper = JSON.parse(body);
                        if(helper.status){
                            var helper_info={
                                user_id:helper.data._id,
                                user_name:helper.data.username,
                                user_type:'helper'
                            };
                            redis_cli.setUserHelper(client,helper_info,users.user_id);
                            redis_cli.setHelperUser(client,users,helper_info.user_id);
                            res.redirect("/helper/"+helper_info.user_id);
                        }else{
                            res.end('no helper free');
                        }
                    }else{
                        console.log(error);
                        res.end('network error');
                    }
                });
            }
        }
    })
});


app.get("/helper/:helper_id",function (req, res) {
    var Cookies = {};
    req.headers.cookie && req.headers.cookie.split(';').forEach(function( Cookie ) {
        var parts = Cookie.split('=');
        Cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
    })
    redis_cli.session(client,Cookies.ci_session,function(response){
        if(!response){
            res.redirect(base_url+login);
        }else{
            var userSerialize = require('./libraries/getCiUser').getUser(response,'login_user');
            var helperSerialize = require('./libraries/getCiUser').getUser(response,'login_helper');
            if(!helperSerialize && !userSerialize){
                return res.redirect(base_url+login);
            }

            if(helperSerialize){
                var user = require('./libraries/serialize').unserialize(helperSerialize);
                if(req.params.helper_id!=user._id){
                    res.end('this page not your home!');
                }else {
                    var helper = {
                        user_id: user._id,
                        user_name: user.username,
                        user_type: 'helper',
                    };
                    redis_cli.helperRelationUser(client, helper.user_id, function (user) {
                        if (user) {
                            var client_user = JSON.parse(user);
                            res.render('chat', {user: client_user, helper: helper, user_type: 'helper'});
                        } else {
                            var client_user = {
                                user_id: 0,
                                user_name: ""
                            }
                            res.render('chat', {user: client_user, helper: helper, user_type: 'helper'});
                        }
                    });
                }
            }
            else if(userSerialize){
                var user = require('./libraries/serialize').unserialize(userSerialize);

                var client_user={
                    user_id:user.user_id,
                    user_name:user.username,
                    user_type:'public'
                };
                redis_cli.userRelationHelper(client,client_user.user_id,function(user){
                    if(user){
                        var helper = JSON.parse(user);
                        res.render('chat',{user:client_user,helper:helper,user_type:'public'});
                    }
                });
            }
        }
    })
});
var getTime=function(){
    var date = new Date();
    return date.getFullYear()+"-"+date.getMonth()+"-"+date.getDay()+" "
        +date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
}
var clients = {
    socket:socketIo,
    form_user_id:0,
    form_user_name:'',
    form_user_type:'',
    to_user_id:0,
    to_user_type:'helper',
    message:'',
    time:getTime()
};
var ptMongo = require("./libraries/ptMongo");
var mongodb = ptMongo.mongodb.init('localhost','27017','paintmore');
var connections = [];
io.on('connection',function(socket){
    //socket.manager.transports[socket.id].socket.setTimeout(15000);
    socket.emit('open',{});
    socket.on('bind',function(msg){
        //链接成功后，客户端加bind
        connections[msg.helper_id+"|"+msg.user_id] = socket;
        socket.link_id = msg.helper_id+"|"+msg.user_id;
        console.log({user_id:msg.user_id,user_name:msg.user_name})
        socket.broadcast.emit('bindUser',{user_id:msg.user_id,user_name:msg.user_name});
    });
    socket.on('message', function(msg){
       if(msg.user_type=='public'){
           clients.form_user_id=msg.user_id;
           clients.form_user_name=msg.user_name;
           clients.form_user_type=msg.user_type;
           clients.to_user_id=msg.helper_id;
           clients.to_user_name=msg.helper_name;
           clients.to_user_type='helper';  //扩展用
           clients.message=msg.msg;
           clients.time=getTime();
           console.log(clients);
        }else{
           clients.form_user_id=msg.helper_id;
           clients.form_user_name=msg.helper_name;
           clients.form_user_type=msg.user_type;
           clients.to_user_id=msg.user_id;
           clients.to_user_name=msg.user_name;
           clients.to_user_type='public';
           clients.message=msg.msg;
           clients.time=getTime();
        }
        clients.sendStatus = 1;
        /*var objClient = msg.helper_id+"|"+msg.user_id;
        if(connections[objClient]){
            socket.broadcast.emit('messages',clients);
        }else{
            clients.sendStatus = 0;
        }*/
        socket.broadcast.emit('messages',clients);
        ptMongo.mongo.insert(mongodb,'paint_helper_message',clients);
    });
    socket.on('disconnect', function(message) {
        delete clients[socket.link_id];
        setTimeout(function(){
            console.log(socket.link_id);
            if(!clients[socket.link_id] && socket.link_id){
                 var redis_cache =  socket.link_id.split("|");
                 if(redis_cache.length==2){
                     redis_cli.setHelperBusy(client,redis_cache[0],0,function(){});
                 }
            }
        },25000);

    });
})
//client.end();




